// pages/notice/notice.js
const appConfig = require('../../config/config.js');
const http = require('../../utils/http.js');
const nav = require('../../utils/navigator.js');
const tip = require('../../utils/tip.js');
const util = require('../../utils/util.js');
// 引入SDK核心类
var QQMapWX = require('../../libs/qqmap-wx-jssdk.js');
var qqmapsdk;
//获取应用实例
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isDisabled:"0px",//隐藏控件属性
    latitude: 0,//地图初次加载时的纬度坐标
    longitude: 0, //地图初次加载时的经度坐标
    noticeId:0,
    noticeType: {}, //发布类型
    txtPhone: '', //手机号码
    txtTitle: '', //标题
    txtName: '', //名字
    txtAddress: '', //详细地址
    txtDescription: '', //走失经过
    status: '1', //启事状态(默认不显示，所以初始化时设置为1)
    provinces: {},
    province: '',
    city: '',
    area: '',
    show: false,
    showCategory: false,
    categoryParents: {},
    categoryChilds: {},
    selectedCategoryParent: '',
    selectedCategoryChild: '',
    selectedColorIndex:-1,
    happendDate: (util.formatTime(new Date()).split(":")[0]+":00").replace("/", "-").replace("/", "-"),
    chooseImages: {},
    videoPath: '',
    radio: {},
    //colorRadio: ['黑色','白色','灰色','花色','棕色','黄色','蓝灰'],
    hiddenColor:true,
    colorItems: [
      { name: '黑色', value: 0 },
      { name: '白色', value: 1 },
      { name: '灰色', value: 2 },
      { name: '花色', value: 3 },
      { name: '棕色', value: 4 },
      { name: '黄色', value: 5 },
      { name: '蓝灰', value: 6 }
    ]
    
  },
  //移动选点
  moveToLocation: function () {
    var that = this;
    var qqMap = new QQMapWX({
      key: appConfig.QQMapWXKey // 必填
    });
    // 打开地图选择位置
    wx.chooseLocation({
      success: function (res) {
        // res.name为地址名称  
        console.log(res);
        that.setData({ 
          txtAddress: res.name, 
          latitude: res.latitude,
          longitude: res.longitude
          });
        // 调用腾讯地图的接口查询当前位置
        qqMap.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function (ret) {
            console.log(ret);

            that.setData({
              province: ret.result.address_component.province,
              city: ret.result.address_component.city,
              area: ret.result.address_component.district,
              //txtAddress: ret.result.formatted_addresses.recommend,
              latitude: res.latitude,
              longitude: res.longitude
            });
            //获取数据更新页面
            console.log(that.data.province, that.data.city, that.data.area);
          },
          fail: function (ret) {
            console.log(ret);
          },
          complete: function (ret) {
            // console.log(res);
          }
        });
      },
      fail: function (err) {
        console.log(err)
      }
    });
  },
  sureSelectAreaListener: function(e) {
    console.log(e)
    var that = this;
    that.setData({
      show: false,
      isDisabled: "0px",
      province: e.detail.currentTarget.dataset.province,
      city: e.detail.currentTarget.dataset.city,
      area: e.detail.currentTarget.dataset.area
    })
  },
  canncelSelectAreaListener:function(e){
    var that = this;
    that.setData({
      show: false,
      isDisabled: "0px"
    })
  },
  chooseAddress: function() {
    var that = this;
    that.setData({
      show: true,
      isDisabled: "1000px"
    })
  },
  // sureSelectCategoryListener: function(e) {
  //   console.log(e)
  //   var that = this;
  //   that.setData({
  //     showCategory: false,
  //     selectedCategoryParent: e.detail.currentTarget.dataset.categoryParent,
  //     selectedCategoryChild: e.detail.currentTarget.dataset.categoryChild,
  //   });
  //   this.canncelSelectAreaListener();
  // },
  chooseCategory: function() {
    // var that = this;
    // that.setData({
    //   showCategory: true
    // });
    //this.chooseAddress();
    var that = this;
    nav.navigateTo("../category/category?callBackPage=category");
  },
  // //日期选择事件
  // sureSelectCalendarListener: function(e) {
  //   console.log(e)
  //   var that = this;
  //   that.setData({
  //     happendDate: e.detail.currentTarget.dataset.year + '-' + e.detail.currentTarget.dataset.month + '-' + e.detail.currentTarget.dataset.day
  //   });
  //   console.log(that.data.happendDate);
  // },
  /**
 * 日历控件绑定函数 
 * 点击日期返回
 */
  onPickerChange: function (e) {
    console.log(e.detail);
    this.setData({
      happendDate: e.detail.dateString +":00"
    });
    this.chooseAddress();
  },
  //图片选择事件
  sureImageUploadListener: function(e) {
    var that = this;
    console.log(e.detail);
    that.setData({
      chooseImages: e.detail
    })
    // wx.uploadFile({
    //   url: appConfig.baseUrl + 'UploadFile/FileUpload', //开发者服务器的 url
    //   filePath: e.detail[0].imageAddress, // 要上传文件资源的路径 String类型！！！
    //   name: 'uploadFile', // 文件对应的 key ,(后台接口规定的关于图片的请求参数)
    //   header: {
    //     'content-type': 'multipart/form-data'
    //   }, // 设置请求的 header
    //   formData: {userId:"1"}, // HTTP 请求中其他额外的参数
    //   success: function (res) {
    //     let datas = JSON.parse(res.data);

    //     console.log(datas);

    //   },
    //   fail: function (res) { }
    // });
  },
  //视频地址
  sureVideoUploadListener: function(e) {
    var that = this;
    that.setData({
      videoPath: e.detail
    })
  },
  //单选
  getradio: function(e) {
    let index = e.currentTarget.dataset.id;
    let radio = this.data.radio;
    for (let i = 0; i < radio.length; i++) {
      this.data.radio[i].checked = false;
    }
    if (radio[index].checked) {
      this.data.radio[index].checked = false;
    } else {
      this.data.radio[index].checked = true;
    }
    let userRadio = radio.filter((item, index) => {
      return item.checked == true;
    })
    this.setData({
      radio: this.data.radio
    })
    console.log(userRadio)
  },
  //控制颜色模态框显示与隐藏
  getColorRadio: function(e) {
    var that = this;
    that.setData({
      hiddenColor: false
    });
    this.chooseAddress();
    //console.log(that.data.selectedColorIndex)
  },
  radioChange(e) {
    var that = this;
    console.log(that.data.colorItems[e.detail.value], e.detail.value)
    
    
    that.setData({
      selectedColorIndex: e.detail.value
    });
  },
  modalColorClose:function(e){
    var that = this;
    that.setData({
      hiddenColor: true
    });
    this.canncelSelectAreaListener();
  },
  //发布按钮点击事件
  btnPublishClick: function(e) {
    var that = this;
    console.log(that.data.chooseImages.length)
    //数据验证
    if (wx.getStorageSync('userId') == [] || wx.getStorageSync('userId') == null || wx.getStorageSync('userId')==undefined)
    {
      tip.showToast('用户信息已过期，请重新登录');return false;
    }
    if (that.data.chooseImages == null || that.data.chooseImages.length == 0 || that.data.chooseImages.length == undefined)
    {
      tip.showToast('您还未上传宠物图片'); return false;
    }
    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
    if (!myreg.test(that.data.txtPhone)) {
        tip.showToast('抱歉，手机号有误');return false;
    }
    // if (that.data.txtName == '' || that.data.province==''
    //   || that.data.city == '' || that.data.area == '' 
    //   || that.data.radio.filter((item, index) => { return item.checked == true; }).length == 0
    //   || that.data.selectedCategoryChild == '' 
    //   || that.data.selectedColorIndex == -1 
    //   || that.data.happendDate == '' || that.data.txtPhone == '')
    // {
    //   tip.showToast('手机号、标题、名称、区域、颜色、性别及时间为必填信息'); return false;
    // }
    
    var date = util.formatTime(new Date());
    console.log(date,that.data.happendDate + ':00')
    if(this.checkDate(date, that.data.happendDate+':00')>0)
    {
      tip.showToast('抱歉，丢失时间不得大于当前时间'); return false;
    }

    if (that.data.noticeType == 0 && (that.data.txtName == '' || that.data.radio.filter((item, index) => { return item.checked == true; }).length == 0 || that.data.selectedCategoryChild == '' || that.data.selectedColorIndex == -1 || that.data.happendDate == '' || that.data.txtPhone == ''))
    {
      tip.showToast('手机号、TA的名字、颜色、性别及时间为必填信息'); return false;
    }
    if (that.data.noticeType == 1 && (that.data.area == '' || that.data.selectedColorIndex == -1 || that.data.happendDate == '' || that.data.txtPhone == '')) {
      tip.showToast('手机号、颜色及时间为必填信息'); return false;
    }
    var ids = [];

    // console.log(that.data.colorRadio.filter((item, index) => {
    //   return item.checked == true;
    // })[0].key)

    wx.showLoading({
      title: '发布中，请稍后...',
    });
    for (var i = 0; i < that.data.chooseImages.length; i++) {

      wx.uploadFile({
        url: appConfig.baseUrl + 'UploadFile/FileUpload', //开发者服务器的 url
        filePath: that.data.chooseImages[i].imageAddress, // 要上传文件资源的路径 String类型！！！
        name: 'uploadFile', // 文件对应的 key ,(后台接口规定的关于图片的请求参数)
        header: {
          'content-type': 'multipart/form-data'
        }, // 设置请求的 header
        formData: {
          userId: wx.getStorageSync('userId')
        }, // HTTP 请求中其他额外的参数
        success: function(res) {
          if (res) {
            let datas = JSON.parse(res.data);
            if (datas && datas.Flag) {
              ids.push(datas.Code);
              //console.log(urls);
              if (ids.length == that.data.chooseImages.length) {
                console.log(ids.join(","));
                http.post(appConfig.baseUrl + 'Notice/PublishNotice', {
                  Id: that.data.noticeId,
                  NoticeType: that.data.noticeType,
                  UserId: wx.getStorageSync('userId'),
                  FileIds: ids.join(","),
                  Title: that.data.txtTitle,
                  PetName: that.data.txtName,
                  ProviceName: that.data.province,
                  CityName: that.data.city,
                  AreaName: that.data.area,
                  Gender: that.data.radio.filter((item, index) => { return item.checked == true; }).length>0? that.data.radio.filter((item, index) => { return item.checked == true; })[0].key:2,
                  CategoryName: that.data.selectedCategoryChild,
                  Color: that.data.selectedColorIndex,
                  Address: that.data.txtAddress,
                  HappenTimeName: that.data.happendDate,
                  Description: that.data.txtDescription,
                  Telphone: that.data.txtPhone,
                  Latitude: that.data.latitude,
                  Longitude: that.data.longitude
                },
                function (res) { 
                  console.log(res.data);
                  wx.hideLoading(); //关闭加载动画
                  if(res.data.Flag==false){
                    tip.showToast(res.data.CodeMsg);
                  }else{
                    //nav.navigateTo("../detail/detail?noticeId=" + res.data.Content);
                    app.subscribeAdapter(wx.getStorageSync('userId'),res.data.Content,()=>wx.reLaunch({ url: '../index/index' }));
                    //wx.reLaunch({ url: '../index/index' });
                  }
                }, function (res) {
                  console.log(res);
                  wx.hideLoading(); //关闭加载动画
                  tip.showToast('发布失败，请稍后再试！');
                }); 
              }
            }
          }
        },
        fail: function(res) {
          wx.hideLoading(); //关闭加载动画
          tip.showToast('发布失败，请稍后再试！');
        }
      });
    }

  },
  //获取验证码
  bindValidClick: function(e) {
    console.log(e);
  },
  //手机号码
  bindTxtPhoneClick: function(e) {
    var that = this;
    that.setData({
        txtPhone: that.validateNumber(e.detail.value)
    });
  },
  //标题
  bindTxtTitleClick: function(e) {
    var that = this;
    that.setData({
      txtTitle: e.detail.value
    });
  },
  //名字
  bindTxtNameClick: function(e) {
    var that = this;
    that.setData({
      txtName: e.detail.value
    });
  },
  //详细位置
  bindTxtAddressClick: function(e) {
    var that = this;
    that.setData({
      txtAddress: e.detail.value
    });
  },
  //走失经过
  bindTxtDescriptionClick: function(e) {
    var that = this;
    that.setData({
      txtDescription: e.detail.value
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //console.log(options.noticeType)
    var that = this;
    
    var qqMap = new QQMapWX({
      key: appConfig.QQMapWXKey // 必填
    });
    //that.moveToLocation();
    that.setData({
      noticeType: options.noticeType, //获取页面跳转传递的参数
      //txtAddress: options.txtAddress
    });
    if(that.data.noticeType==0)
    {
      wx.setNavigationBarTitle({
          title: '寻宠信息'
      });
      that.setData({radio : [{"key": "0",'value': '弟弟'},{"key": "1",'value': '妹妹'}]});
    }else
    {
      wx.setNavigationBarTitle({
        title: '寻主信息'
      });
      that.setData({radio: [{ "key": "0", 'value': '弟弟' }, { "key": "1", 'value': '妹妹' },
      {"key": "2",'value': '未知'}]});
    }
    //获取地理位置
    app.getLocationInfo(function (data) { 
      // 调用腾讯地图的接口查询当前位置
      qqMap.reverseGeocoder({
        location: {
          latitude: data.latitude,
          longitude: data.longitude
        },
        success: function (res) {
          console.log(res);

          that.setData({
            province: res.result.address_component.province,
            city: res.result.address_component.city,
            area: res.result.address_component.district,
            txtAddress: res.result.formatted_addresses.recommend,
            latitude: data.latitude,
            longitude: data.longitude
          });
          //获取数据更新页面
          console.log(res.result.address);
        },
        fail: function (res) {
          console.log(res);
        },
        complete: function (res) {
          // console.log(res);
        }
      });
     });

     //从编辑按钮跳转过来 根据noticeid加载数据
    var notice_id = options.noticeId;
    if (notice_id !=null)
    {
      wx.showLoading({
        title: '玩命加载中...',
      });
      http.post(appConfig.baseUrl + 'Notice/GetNoticeDetail', {
        id: options.noticeId,
        UserId: wx.getStorageSync('userId')
      }, function (res) {
        if (res) {
          console.log('编辑详情',res.data);
          wx.hideLoading(); //关闭加载动画
          if (!res.data) {
            tip.showToast('抱歉，未获取到该启事信息', 'none', function (res) {
              setTimeout(function () {
                nav.redirectTo("../index/index");
              }, 2000);
            });
            return false;
          }
          var imgs = []; //详情图片
          //var s_imgs = []; //列表图片
          if (res.data && res.data.FileList) {
            for (var i = 0; i < res.data.FileList.length; i++) {
              var names = res.data.FileList[i].Url.split(".");
              //console.log(names)
              var file_name = names[0]+ "." + names[1] + "." + names[2];
              var pfix = res.data.FileList[i].Url.split(".")[3];
              imgs.push(res.data.FileList[i].Url);
              //s_imgs.push(file_name + "_m." + pfix);
            }
            console.log(imgs)
            var pet_imgupload = that.selectComponent("#pet_imgupload");
            pet_imgupload.loadImageEvent(imgs)
          }

          that.setData({
            txtPhone: res.data.Telphone,
            txtName: res.data.PetName, //名字
            txtAddress: res.data.Address, //详细地址
            txtDescription: res.data.Description, //走失经过
            province: res.data.ProviceName,
            city: res.data.CityName,
            area: res.data.AreaName,
            happendDate: res.data.HappenTimeName,
            selectedColorIndex: res.data.Color,
            selectedCategoryParent: res.data.CategoryPatentName,
            selectedCategoryChild: res.data.CategoryName,
            noticeId: options.noticeId,
            status: res.data.Status,
          });
          let index = res.data.Gender;
          let radio = that.data.radio;
          for (let i = 0; i < radio.length; i++) {
            that.data.radio[i].checked = false;
          }
          if (radio[index].checked) {
            that.data.radio[index].checked = false;
          } else {
            that.data.radio[index].checked = true;
          }
          let userRadio = radio.filter((item, index) => {
            return item.checked == true;
          })
          that.setData({
            radio: that.data.radio
          });
        }
      }, function (res) {

      });
    }
  },
  bindPositionClick:function(e){
    this.moveToLocation();
  },
  /**发布人关闭启事 */
  bindCompleteClick:function(e)
  {
    var that = this;
    http.post(appConfig.baseUrl + 'Notice/SetComplete', {
      Id: that.data.noticeId,
      UserId: wx.getStorageSync('userId')
    }, function(res) {
      if (res) {
        //console.log(res.data);
        //tip.showToast(res.data.CodeMsg);
        tip.showModal('提示',res.data.CodeMsg,()=>{
          nav.navigateTo("../detail/detail", {
            noticeId: that.data.noticeId
          });
        });
      }
    }, function(res) {
      tip.showToast('系统繁忙，请稍后再试！');
    });
  },
  checkDate: function (startTime, endTime) {
    //日期格式化
    var start_date = new Date(startTime.replace(/-/g, "/"));
    var end_date = new Date(endTime.replace(/-/g, "/"));
    //转成毫秒数，两个日期相减
    var days = end_date.getTime() - start_date.getTime();
    //转换成天数
    var day = parseInt(days / (1000 * 60 * 60 * 24));
    //do something
    //console.log(days);
    return days;
  },
  validateNumber(val) {
      return val.replace(/\D/g, '')
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})